<template>
  <div class="image__container" :style="containerStyle">
    <img :src="currentSrc" ref="image" :style="imgStyle" alt />
  </div>
</template>
<script>
import NoImage from "@/assets/no-image.svg";
import Scale from "@/common/scale";
let load = function(src) {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.onload = function() {
      resolve(img);
    };
    img.onerror = function(e) {
      reject(e);
    };
    img.src = src;
  });
};
export default {
  name: "AutoImage",
  props: {
    width: Number,
    height: Number,
    size: {
      type: String,
      default: "cover",
      validate(val) {
        return /^(cover)|(contain)$/.test(val);
      }
    },
    src: String
  },
  data() {
    return {
      seed: 380 / 1920,
      naturalWidth: 0,
      naturalHeight: 0,
      vertical: false,
      currentSrc: NoImage,
      noImage: NoImage
    };
  },
  computed: {
    containerStyle() {
      return {
        height: window.lib.flexible.px2rem(this.height) + "rem",
        width: window.lib.flexible.px2rem(this.width) + "rem"
      };
    },
    imgStyle() {
      let style = {
        width: window.lib.flexible.px2rem(this.naturalWidth) + "rem",
        height: window.lib.flexible.px2rem(this.naturalHeight) + "rem"
      };
      if (this.vertical) {
        style.top =
          window.lib.flexible.px2rem((this.height - this.naturalHeight) / 2) +
          "rem";
      } else {
        style.left =
          window.lib.flexible.px2rem((this.width - this.naturalWidth) / 2) +
          "rem";
      }
      return style;
    }
  },
  async mounted() {
    this.loadImg();
  },
  methods: {
    async loadImg() {
      let img;
      let src;
      try {
        src = this.src;
        img = await load(src);
      } catch (e) {
        src = this.noImage;
        img = await load(src);
      }
      let w = img.naturalWidth || img.width || img.offsetWidth;
      let h = img.naturalHeight || img.height || img.offsetHeight;
      let { width, height, vertical } = Scale(
        this.width,
        this.height,
        w,
        h,
        this.size
      );
      this.naturalWidth = width;
      this.naturalHeight = height;
      this.vertical = vertical;
      this.currentSrc = src;
    }
  }
};
</script>
<style lang="stylus">
.image__container {
  display: inline-block;
  vertical-align: middle;
  position: relative;
  overflow: hidden;

  img {
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>